using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace StudentManagementApplication
{
    public partial class FrmStudentInfo : Form
    {
        List<Entities.Class> classList = new List<Entities.Class>();
        List<Entities.Student> studentList = new List<Entities.Student>();
        List<Entities.Person> personList = new List<Entities.Person>();
        Business.ClassService classService = new Business.ClassService();
        Business.PersonService personService = new Business.PersonService();
        Business.StudentService studentService = new Business.StudentService();
        Business.LoginService loginService = new Business.LoginService();
        Business.MarksService marksService = new Business.MarksService();
        Business.RollcallService rollcallService = new Business.RollcallService();
        Business.FeeService feeService = new Business.FeeService();
        Entities.Person person = null;
        Entities.Student student = null;
        Entities.Login account = null;
        Entities.Marks marks = null;
        Entities.Fee fee = null;
        int iIndex = 0;
        
        private void InitializeClass()
        {
            classList = classService.GetAllClasses();
            foreach (Entities.Class _class in classList)
            {
                cmbClass.Items.Add(_class.ClassID +"--"+_class.ClassName);
            }
            cmbClass.SelectedIndex = 0;
        }

        private void InitializeStudent()
        {
            if (dgvStudents.Rows.Count > 1)
            {
                int iCount = dgvStudents.Rows.Count - 1;
                for (int i = 0; i < iCount; i++)
                {
                    dgvStudents.Rows.RemoveAt(0);
                }
            }
            if (cmbClass.Text != string.Empty)
            {
                studentList = studentService.GetStudentsByClassID(cmbClass.Text.Substring(0, 6));
                personList = personService.GetPersonWithClassID(cmbClass.Text.Substring(0, 6));
            }
            else
            {
                studentList = studentService.GetAllStudents();
                personList = personService.GetPersonWithRoleID("R14");
            }
            for (int i = 0; i < personList.Count; i++)
            {
                string[] temp = { personList[i].PersonID, personList[i].PersonName, personList[i].PersonBirth.ToShortDateString(), personList[i].PersonAdd, personList[i].PersonPhone, personList[i].PersonMail, personList[i].Picture.Length > 6 ? personList[i].Picture.Substring(6) : "", studentList[i].ClassID };
                dgvStudents.Rows.Add(temp);
            }
            dgvStudents[0, iIndex].Selected = true;
        }

        private void FindStudentByStudentID(string sStudentID)
        {
            studentList = studentService.GetAllStudents();
            personList = personService.GetPersonWithRoleID("R14");
            if (dgvStudents.Rows.Count > 1)
            {
                int iCount = dgvStudents.Rows.Count - 1;
                for (int i = 0; i < iCount; i++)
                {
                    dgvStudents.Rows.RemoveAt(0);
                }
            }
            for(int i=0;i<studentList.Count;i++)
            {
                if (studentList[i].StudentID.ToLower().Contains(sStudentID))
                {
                    string[] temp = { personList[i].PersonID, personList[i].PersonName, personList[i].PersonBirth.ToShortDateString(), personList[i].PersonAdd, personList[i].PersonPhone, personList[i].PersonMail, personList[i].Picture.Length > 6 ? personList[i].Picture.Substring(6) : "", studentList[i].ClassID };
                    dgvStudents.Rows.Add(temp);
                }
            }
            iIndex = 0;
            dgvStudents[0, iIndex].Selected = true;
            if (dgvStudents.Rows.Count > 1) FindStudent(dgvStudents.Rows[iIndex].Cells[0].Value.ToString());
        }

        private void FindStudent(string sStudentID)
        {
            person = new Entities.Person();
            student = new Entities.Student();
            person = personService.GetPersonByPersonID(sStudentID);
            student = studentService.GetStudentByStudentID(sStudentID);
            txtStudentID.Text = student.StudentID;
            txtName.Text = person.PersonName;
            dtpBirthDay.Value = person.PersonBirth.Date;
            txtAddress.Text = person.PersonAdd;
            txtPhone.Text = person.PersonPhone;
            txtMail.Text = person.PersonMail;
            if (person.Picture.Length > 6)
            {
                txtPicture.Text = person.Picture.Substring(6);
                picStudent.ImageLocation = person.Picture;
            }
            else
            {
                txtPicture.Text = string.Empty;
                picStudent.ImageLocation = string.Empty;
            }
        }

        private void UpdateStudentInfo()
        {
            if (Test())
            {
                student.ClassID = (cmbClass.Text.Length > 6 ? cmbClass.Text.Substring(0, 6) : cmbClass.Text);
                person.PersonName = txtName.Text;
                person.PersonBirth = dtpBirthDay.Value.Date;
                person.PersonAdd = txtAddress.Text;
                person.PersonPhone = txtPhone.Text;
                person.PersonMail = txtMail.Text;
                person.Picture = txtPicture.Text;
                try
                {
                    studentService.UpdateStudent(student);
                    personService.UpdatePerson(person);
                    InitializeStudent();
                }
                catch
                {
                    MessageBox.Show("Update unsuccessfully", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private bool IsNumber(string sPhone)
        {
            try
            {
                int.Parse(sPhone);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool Test()
        {
            bool bResult = true;
            string sInformation = string.Empty;
            if (txtName.Text == string.Empty)
                sInformation += "Full Name is empty" + "\n";
            if ((DateTime.Now.Year - dtpBirthDay.Value.Year) < 18)
                sInformation += "The ages have to be greater than 18" + "\n";
            if (txtAddress.Text == string.Empty)
                sInformation += "Address is empty" + "\n";
            if (txtPhone.Text == string.Empty)
                sInformation += "Phone is empty" + "\n";
            if (txtPhone.Text.Length != 7)
                if (txtPhone.Text.Length != 10)
                    if (txtPhone.Text.Length != 11)
                        sInformation += "Number phone have to have 7,10 or 11 chars" + "\n";
            if (!IsNumber(txtPhone.Text))
                sInformation += "Type of phone have to be integer" + "\n";
            if (txtMail.Text == string.Empty)
                sInformation += "Mail is empty" + "\n";
            if (!txtMail.Text.Contains("@"))
                sInformation += "Mail isn't legal" + "\n";
            if (cmbClass.Text == string.Empty)
                sInformation += "ClassID is empty" + "\n";
            if (sInformation != string.Empty)
            {
                MessageBox.Show(sInformation, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                bResult = false;
            }
            return bResult;
        }

        private void InsertLoginAndPersonInfo()
        {
            person = new Entities.Person();
            account = new Entities.Login();
            person.PersonName = txtName.Text;
            person.PersonBirth = dtpBirthDay.Value.Date;
            person.PersonAdd = txtAddress.Text;
            person.PersonPhone = txtPhone.Text;
            person.PersonMail = txtMail.Text;
            person.Picture = txtPicture.Text;
            person.LoginID = CreateLoginAutomatically(txtName.Text.ToLower());
            account.LoginID = person.LoginID;
            account.RoleID = "R14";
            account.State = 1;
            loginService.InsertAccount(account);
            personService.InsertPerson(person);
        }

        private void InsertMarksOfStudent(string sStudentID)
        {
            marks = new Entities.Marks();
            marks.StudentID = sStudentID;
            marks.Mark = 0;
            marksService.InsertMarks(marks);
        }

        private void InsertFeeOfStudent(string sStudentID)
        {
            fee = new Entities.Fee();
            fee.StudentID = sStudentID;
            fee.FeePaid = 0;
            fee.FeeType = "T11";
            feeService.InsertFee(fee);
        }

        private void InsertStudentInfo()
        {
            if (Test())
            {
                student = new Entities.Student();
                student.ClassID = cmbClass.Text.Substring(0, 6);
                InsertLoginAndPersonInfo();
                person = new Entities.Person();
                person = personService.GetNewPersonID();
                try
                {
                    student.StudentID = person.PersonID;
                    studentService.InsertStudent(student);
                    InsertMarksOfStudent(student.StudentID);
                    InsertFeeOfStudent(student.StudentID);
                    iIndex = dgvStudents.Rows.Count - 1;
                    InitializeStudent();
                }
                catch
                {
                    MessageBox.Show("Insert unsuccessfully", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    loginService.DeleteAccount(account.LoginID);
                    personService.DeletePerson(person.LoginID);
                }
            }
        }

        private void DeleteStudent()
        {
            if (person != null && dgvStudents.CurrentRow.Index >= 0)
            {
                if (MessageBox.Show("You want to delete.Are you sure?", "Information", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    rollcallService.DeleteRollcallByStudentID(student.StudentID);
                    marksService.DeleteMarks(student.StudentID);
                    feeService.DeleteFee(student.StudentID);
                    studentService.DeleteStudent(person.PersonID);
                    personService.DeletePerson(person.PersonID);
                    loginService.DeleteAccount(person.LoginID);
                    if (iIndex > 0) iIndex--;
                    else iIndex = 0;
                    InitializeStudent();
                    FindStudent(dgvStudents.Rows[iIndex].Cells[0].Value.ToString());
                }
            }
        }

        private string CreateLoginAutomatically(string sName)
        {
            char[] charArray = { ' ' };
            string[] nameArray = sName.Split(charArray);
            string sLoginID = string.Empty;
            while (true)
            {
                sLoginID = string.Empty;
                Random random = new Random();
                sLoginID += nameArray[nameArray.Length - 1] + nameArray[0] + random.Next(1, 100).ToString();
                Entities.Login account = loginService.GetAccountByLoginID(sLoginID);
                if (account == null)
                    break;
            }
            return sLoginID;
        }

        private void RefreshData()
        {
            txtStudentID.Text = string.Empty;
            txtName.Text = string.Empty;
            dtpBirthDay.Value = DateTime.Now.Date;
            txtAddress.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtMail.Text = string.Empty;
            txtPicture.Text = string.Empty;
            picStudent.Image = null;
            picStudent.ImageLocation = string.Empty;
        }

        public FrmStudentInfo()
        {
            InitializeComponent();
        }

        private void FrmStudentInfo_Load(object sender, EventArgs e)
        {
            InitializeClass();
            InitializeStudent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.InitialDirectory = "Image";
            file.FileName = txtPicture.Text;
            file.ShowDialog();
            string sFileName = file.FileName;
            txtPicture.Text = sFileName.Substring(sFileName.IndexOf("Image") + 6);
            picStudent.ImageLocation = sFileName;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            FindStudentByStudentID(txtStudentID.Text.ToLower());
        }

        private void dgvStudents_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (rdoUpdate.Checked && dgvStudents.CurrentRow.Index < dgvStudents.Rows.Count - 1)
            {
                iIndex = dgvStudents.CurrentRow.Index;
                string sStudentID = dgvStudents.CurrentRow.Cells[0].Value.ToString();
                FindStudent(sStudentID);
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (student != null)
                UpdateStudentInfo();
            else
                MessageBox.Show("You should choose the student you want to change");
        }

        private void rdoInsert_CheckedChanged(object sender, EventArgs e)
        {
            RefreshData();
            txtStudentID.Enabled = false;
            btnInsert.Enabled = true;
            pictureBox1.Enabled = false;
            btnDelete.Enabled = false;
            btnUpdate.Enabled = false;
        }

        private void rdoUpdate_CheckedChanged(object sender, EventArgs e)
        {
            RefreshData();
            txtStudentID.Enabled = true;
            btnInsert.Enabled = false;
            pictureBox1.Enabled = true;
            btnDelete.Enabled = true;
            btnUpdate.Enabled = true;
            FindStudent(dgvStudents.Rows[iIndex].Cells[0].Value.ToString());
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            InsertStudentInfo();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (student != null)
            {
                DeleteStudent();
            }
            else
                MessageBox.Show("You should choose the student you want to delete");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            iIndex = 0;
            InitializeStudent();
        }
    }
}